<template>
  <view class="my-gift-container">
    <!-- 顶部标签切换 -->
    <view class="tab-header">
      <view
        class="tab-item"
        :class="{ active: currentTab === 0 }"
        @tap="switchTab(0)"
      >
        <text>未领取</text>
        <view class="active-line" v-if="currentTab === 0"></view>
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 1 }"
        @tap="switchTab(1)"
      >
        <text>已领取</text>
        <view class="active-line" v-if="currentTab === 1"></view>
      </view>
    </view>

    <!-- 礼包列表 -->
    <view class="gift-list" v-if="isShowGiftList">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-wrapper">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="giftList.length === 0" class="empty-wrapper">
        <text class="empty-text">暂无礼包</text>
      </view>

      <!-- 礼包列表 -->
      <view
        v-else
        class="gift-item"
        v-for="(item, index) in giftList"
        :key="index"
      >
        <view class="gift-info">
          <view class="amount">{{ item.amount }}包沐浴露</view>
          <view class="publisher">
            发放人：{{ item.sender_name }} (ID:{{ item.sender_id }})
          </view>
          <view class="date" v-if="item.status == 1">
            领取日期：{{ item.receive_date }}
          </view>
          <view class="date" v-if="item.status == 0">
            发放日期：{{ item.publishDate }}
          </view>
          <view class="receiver" v-if="item.receiver && item.status === 1">
            <image
              class="avatar"
              :src="item.receiver.avatar"
              mode="aspectFill"
            ></image>
            <text
              >领取人：{{ item.receiver.nickname }} (ID:
              {{ item.receiver.uid }})</text
            >
          </view>
        </view>
        <view class="gift-status">
          <view
            class="status-tag"
            :class="{
              received: item.status === 1,
              pending: item.status === 0,
            }"
          >
            {{ item.status === 1 ? "已领取" : "待领取" }}
          </view>
          <view
            class="share-btn"
            v-if="item.status === 0"
            @tap="shareGift(item)"
          >
            <uni-icons type="paperplane" size="16" color="#00a971"></uni-icons>
            <text class="share-text">我要分享</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { getMyGifts, receiveGift } from "../../api/gift";

// 声明 uni 对象
declare const uni: any;

// 礼包数据类型
interface GiftItem {
  id: number;
  send_id: number;
  sender_id: number;
  receiver_id: number;
  amount: number;
  receive_date: string | null;
  status: number; // 0-未领取, 1-已领取
  created_at: number;
  sender_name: string;
  publishDate?: string;
  receiver?: {
    uid: number;
    nickname: string;
    avatar: string;
  };
}

const currentTab = ref(0);
const allGiftList = ref<GiftItem[]>([]);
const loading = ref(false);
const isShowGiftList = ref(true);

// 获取我的礼包列表
const fetchMyGifts = async () => {
  try {
    loading.value = true;
    const res = await getMyGifts({
      status: currentTab.value,
      page: 1,
      pageSize: 10,
    });
    if (res.result === 1 && Array.isArray(res.data.data)) {
      // 格式化数据
      allGiftList.value = res.data.data.map((item: any) => {
        if (item.receive_date) {
          //时间戳转换
          item.receive_date = new Date(
            item.receive_date * 1000
          ).toLocaleDateString();
        } else {
          item.receive_date = "-";
        }
        // 处理时间格式
        let publishDate = "--";
        if (item.created_at) {
          // 兼容iOS的日期格式处理
          let dateString = item.created_at;
          // 如果是 "yyyy-MM-dd HH:mm:ss" 格式，转换为 "yyyy/MM/dd HH:mm:ss"
          if (
            typeof dateString === "string" &&
            dateString.includes("-") &&
            dateString.includes(" ")
          ) {
            dateString = dateString.replace(/-/g, "/");
          }
          const d = new Date(dateString);
          if (!isNaN(d.getTime())) {
            publishDate = `${d.getFullYear()}-${String(
              d.getMonth() + 1
            ).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
          }
        }

        return {
          ...item,
          publishDate,
          publisher: item.sender?.nickname || "未知用户",
          publisherId: item.sender_id,
        };
      });
    } else {
      uni.showToast({
        title: res.msg || "获取数据失败",
        icon: "none",
      });
      allGiftList.value = [];
    }
  } catch (error) {
    console.error("获取礼包列表失败:", error);
    uni.showToast({
      title: "网络错误",
      icon: "none",
    });
    allGiftList.value = [];
  } finally {
    loading.value = false;
  }
};

// 根据标签筛选礼包列表
const giftList = computed(() => {
  return allGiftList.value.filter((item) =>
    currentTab.value === 0 ? item.status === 0 : item.status === 1
  );
});

// 切换标签
const switchTab = (index: number) => {
  currentTab.value = index;
  fetchMyGifts(); // 切换tab时重新加载数据
};

// 分享礼包
const shareGift = (gift: GiftItem) => {
  uni.navigateTo({
    url: `/subpages/gift/myShare?giftId=${gift.id}`,
  });

  // uni.showModal({
  //   title: "模拟接收礼包",
  //   content: "请输入接收人ID（测试用）",
  //   editable: true,
  //   placeholderText: "接收人ID",
  //   success: async (res: any) => {
  //     if (res.confirm && res.content) {
  //       const receive_id = res.content.trim();
  //       if (!receive_id) {
  //         uni.showToast({ title: "请输入接收人ID", icon: "none" });
  //         return;
  //       }
  //       try {
  //         uni.showLoading({ title: "领取中..." });
  //         const result = await receiveGift({
  //           gift_receive_id: gift.id,
  //           receive_id,
  //         });
  //         if (result.result === 1) {
  //           uni.showToast({ title: "领取成功", icon: "success" });
  //           fetchMyGifts();
  //         } else {
  //           uni.showToast({ title: result.msg || "领取失败", icon: "none" });
  //         }
  //       } catch (e) {
  //         uni.showToast({ title: "网络错误", icon: "none" });
  //       } finally {
  //         uni.hideLoading();
  //       }
  //     }
  //   },
  // });
};

// 页面显示时刷新数据
onShow(() => {
  fetchMyGifts();
});
</script>

<style lang="scss" scoped>
.my-gift-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.tab-header {
  display: flex;
  background: #ffffff;
  padding: 0 40rpx;
  position: sticky;
  top: 0;
  z-index: 1;

  .tab-item {
    flex: 1;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    font-size: 28rpx;
    color: #666666;

    &.active {
      color: #00a971;
      font-weight: 500;
    }

    .active-line {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 48rpx;
      height: 4rpx;
      background: #00a971;
      border-radius: 2rpx;
    }
  }
}

.gift-list {
  padding: 20rpx;

  .loading-wrapper,
  .empty-wrapper {
    padding: 80rpx 0;
    text-align: center;

    .loading-text,
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .gift-item {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .gift-info {
      flex: 1;

      .amount {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
        margin-bottom: 16rpx;
      }

      .publisher,
      .date {
        font-size: 26rpx;
        color: #666666;
        margin-bottom: 8rpx;
      }

      .receiver {
        display: flex;
        align-items: center;
        margin-top: 16rpx;

        .avatar {
          width: 48rpx;
          height: 48rpx;
          border-radius: 24rpx;
          margin-right: 12rpx;
        }

        text {
          font-size: 26rpx;
          color: #666666;
        }
      }
    }

    .gift-status {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      min-width: 140rpx;

      .status-tag {
        font-size: 24rpx;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
        margin-bottom: 16rpx;

        &.pending {
          background: rgba(0, 169, 113, 0.1);
          color: #00a971;
        }

        &.received {
          background: #f5f5f5;
          color: #999999;
        }
      }

      .share-btn {
        display: flex;
        align-items: center;
        padding: 12rpx 24rpx;
        background: #ffffff;
        border: 2rpx solid #00a971;
        border-radius: 32rpx;
        color: #00a971;
        font-size: 24rpx;
        cursor: pointer;

        .share-text {
          margin-left: 8rpx;
          color: #00a971;
        }
      }
    }
  }
}
</style>
